package com.sso.client.filter;/**
 * Created by dell on 2020/4/17.
 */

import com.sso.common.utils.HttpUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginFilter
 * @Description //TODO
 * @Author ljr
 * @Date 2020/4/17 23:12
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/login")
public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) request;
        HttpServletResponse httpServletRespons= (HttpServletResponse) response;
        // 检验是否登录
        Boolean b=(Boolean) httpServletRequest.getSession().getAttribute("isLogin");
        if (b!=null&&b){
            chain.doFilter(request,response);
            return;
        }
        //验证token
        String token=request.getParameter("token");
        if (StringUtils.isNotBlank(token)){
            //检验是否正确
            Boolean verifyToken =(Boolean) HttpUtils.postVerifyToken("http://localhost:8082/verifyToken?token=", token);
            if (verifyToken){
                httpServletRequest.getSession().setAttribute("isLogin",true);
                httpServletRespons.sendRedirect("/?username=123");
                return;
            }
        }
        String url=((HttpServletRequest) request).getRequestURL().toString();
        httpServletRespons.sendRedirect("http://localhost:8082/toLogin?url="+url);
    }
    public void destroy() {
        System.out.println("des");
    }
}
